import { useEffect, useMemo } from "react"
import { useDispatch, useSelector } from 'react-redux'
import {
  queryAppDefinitionAction,
  setCurAppAction,
  queryAppProcessesAction
} from "../store/actions/appDefAction"

const useAppDef = () => {
  const dispatch = useDispatch()

  const appDefList = useSelector(state => state.appDef.list)
  const curApp = useSelector(state => state.appDef.curApp)

  // 切换当前app
  const handleChangeCurApp = (appKey) => {
    localStorage.setItem('appKey', appKey)
    dispatch(setCurAppAction(appKey))
  }

  const appList = useMemo(() => {
    return appDefList ? appDefList.filter(el => !!el.appDefinitionId) : []
  }, [appDefList])

  // 加载app列表
  useEffect(() => {
    if(!appDefList){
      dispatch(queryAppDefinitionAction())
    }
  }, [])

  // app列表加载完成后设置当前app
  useEffect(() => {
    if (appList.length) {
      const appKey = localStorage.getItem('appKey')
      if (appKey) {
        dispatch(setCurAppAction(appKey))
        dispatch(queryAppProcessesAction(appKey))
      }
    }
  }, [appList])

  return {
    appList,
    curApp,
    handleChangeCurApp,
  }
}

export default useAppDef